package com.atguigu.gmall.activity.controller;

import com.atguigu.gmall.activity.redis.listener.CacheHelper;
import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 李旭
 * @date 2021/12/7 16:00
 * @Description:
 */
@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillGoodsController {


    @Autowired
    private SeckillGoodsService seckillGoodsService;
    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private RedisTemplate redisTemplate;

    //查询秒杀频道页面的 秒杀商品集合
    @GetMapping("/list")
    public List<SeckillGoods> list(){

        return seckillGoodsService.list();
    }
    //查询秒杀详情页面
    @GetMapping("/detail/{skuId}")
    public SeckillGoods detail(@PathVariable Long skuId){

        return seckillGoodsService.detail(skuId);
    }
    //获取抢购码
    @GetMapping("/auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable Long skuId, HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        SeckillGoods seckillGoods = seckillGoodsService.detail(skuId);
        //1:时间
        //2:状态码
        if(!"1".equals(seckillGoods.getStatus())){//硬编码问题
            return Result.fail().message("此商品已经下架了");
        }
        //3:库存

        //4:此商品可以抢购
        //发抢购码
        //1:UUID   +  Redis
        //2: MD5(userId+“：” +skuId) 算法
        String skuIdStr = MD5.encrypt(userId + ":" + skuId);
        return Result.ok(skuIdStr);
    }

    //开始秒杀
    @PostMapping("/auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable Long skuId, String skuIdStr, HttpServletRequest request){
//        1、校验抢购码
        String userId = AuthContextHolder.getUserId(request);
        String encrypt = MD5.encrypt(userId + ":" + skuId);
        if(StringUtils.isEmpty(skuIdStr) || !skuIdStr.equals(encrypt)){
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }
//        2、校验状态位
        Object status = CacheHelper.get(skuId.toString());
        if(!"1".equals(status)){
            return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
        }
//        3、发消息
        UserRecode userRecode = new UserRecode();
        userRecode.setSkuId(skuId);
        userRecode.setUserId(userId);
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_SECKILL_USER,MqConst.ROUTING_SECKILL_USER,
                userRecode);
//        4、Result.ok
        return Result.ok();
    }
    //查询结果 3S执行一次
    @GetMapping("/auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable Long skuId,HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
//        1、用户是否来过
        Object r1 = redisTemplate.opsForValue().get(RedisConst.SECKILL_USER + userId + ":" + skuId);
        if(null == r1){
            //用户没有来过
            Object r2 = CacheHelper.get(skuId.toString());
            if("1".equals(r2)){
                //        2、返回排队中
                return Result.build(null,ResultCodeEnum.SECKILL_RUN);
            }else{
                //        3、校验是否有货
                return Result.build(null,ResultCodeEnum.SECKILL_FINISH);
            }

        }else{
            //用户来过了
//        4、查询是否已经下单
            Object r3 = redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS_USERS +
                    userId + ":" + skuId);
            if(null != r3){
                //以用户已经下过订单了
                return Result.build(null,ResultCodeEnum.SECKILL_ORDER_SUCCESS);
            }else{
//        5、查询抢购资格
                Object r4 = redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS +
                        userId + ":" + skuId);
                if(null == r4){
                    //抢购失败  leftpop == null  216
                    return Result.build(null,ResultCodeEnum.SECKILL_FAIL);
                }else{
                    //抢购成功 215
                    return Result.build(null,ResultCodeEnum.SECKILL_SUCCESS);
                }
            }
        }
    }
}
